package com.example.filter;

import com.example.utils.CurrentHolder;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * TokenFilter 类的描述信息
 * 过滤器
 *
 * @author 12427
 * @since 2025/6/8 11:04
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        1.获取请求路径
        StringBuffer url = request.getRequestURL();
//        2.判断请求路径是否是登录请求
        if (url.toString().contains("/login")) {
            log.info("登录请求");
            filterChain.doFilter(servletRequest, servletResponse);//放行
            return;
        }
//        3.获取请求头中的token
        String token = request.getHeader("token");
//        4.判断token是否存在 ，不存在返回401
        if (token == null || token.isEmpty()) {
            log.info("请求头中缺少token");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401状态  跳转到登录
            return;
        }
//        5.如果存在,校验令牌,校验失败返回401
        try {
            Claims claims = JwtUtils.parseJWT(token);
//            获取id
            Integer empid = Integer.valueOf(claims.get("id").toString());
//            将id  存入ThreadLocal(线程自带唯一)

            log.info("获取到用户id{}存入ThreadLocal",empid);
            CurrentHolder.setCurrentId(empid);
        } catch (Exception e) {
            log.info("请求头中缺少token");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
//        6.放行请求
        filterChain.doFilter(servletRequest, servletResponse);
//        过滤器链  按照文件排序

//        删除获得的ThreadLocal  内容
        CurrentHolder.remove();
    }
}
